package com.lovo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.bean.UserInfosBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResponseResult;
import com.lovo.result.ResultCode;
import com.lovo.result.UserValid;
import com.lovo.service.IUserInfosService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bdk
 * @since 2021-03-02
 */
@RestController
@RequestMapping("/users")
@ResponseResult
@Api("用户注册和登录以及查看用户信息的控制器")
public class UserInfosController {
    @Resource
    private IUserInfosService userInfoService;
    @PostMapping
    @ApiOperation(value = "注册请求")
    public Object register(@RequestBody UserInfosBean userInfoBean){
        // 使用SHA256加密
        userInfoBean.setUserPass(DigestUtils.sha256Hex(userInfoBean.getUserPass()));
        userInfoService.save(userInfoBean);
        return null;
    }
    @ApiOperation(value = "显示所有用户")
    @GetMapping
    @UserValid
    public Object showAll(Integer page,Integer size){
//        return userInfoService.list();
        return userInfoService.selectAll(page,size);
    }

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Object login(HttpSession session, String userName, String userPass) throws GlobalHandleException {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_name",userName);
        wrapper.eq("user_pass",DigestUtils.sha256Hex(userPass));
        UserInfosBean userInfoBean = userInfoService.getOne(wrapper);
        if(userInfoBean == null){
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }
        session.setAttribute("user",userInfoBean);
        return userInfoBean;
    }
    @GetMapping("/removeSession")
    public Object removeSession(HttpSession session){
        session.setAttribute("user",null);
        return null;
    }

    /**
     * 从session中获取用户对象
     * @return
     */
    @GetMapping("/session")
    @UserValid
    public Object getUserWithSession(HttpSession session){
        return session.getAttribute("user");
    }


}

